package cn.sangyy.basic.utils;

import cn.sangyy.basic.common.IdName;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;

import java.util.*;

public class SearchUtil {


    /**
     * 处理terms聚合   id  name
     * @param aggregations
     * @return
     */
    public static Map<String,Object> getMapByAgg(Aggregations aggregations){
        Map<String,Object> result = new HashMap<>();
        Map<String, Aggregation> map1 = aggregations.getAsMap();
        Set<Map.Entry<String, Aggregation>> entries1 = map1.entrySet();

        for (Map.Entry<String, Aggregation> e : entries1) {
            Terms longTerms = (Terms) e.getValue();
            List<? extends Terms.Bucket> buckets1 = longTerms.getBuckets();
            List<IdName> idNames = new ArrayList<>();
            for (Terms.Bucket b : buckets1) {
                IdName idName = new IdName();
                String id = b.getKeyAsString();
                idName.setId(Long.valueOf(id));
                Aggregations aggregations1 = b.getAggregations();
                Map<String, Aggregation> map2 = aggregations1.getAsMap();
                Set<Map.Entry<String, Aggregation>> entries2 = map2.entrySet();
                Iterator<Map.Entry<String, Aggregation>> iterator = entries2.iterator();
                Map.Entry<String, Aggregation> entry = iterator.next();
                Terms StringTerms = (Terms) entry.getValue();
                List<? extends Terms.Bucket> buckets2 = StringTerms.getBuckets();
                if (buckets2.size() > 0) {
                    String name = buckets2.get(0).getKeyAsString();
                    idName.setName(name);
                }
                idNames.add(idName);
            }
            result.put(e.getKey(), idNames);
        }
        return result;
    }
}